package com.hoolai.qps.mina.proto;

import java.io.IOException;
import java.net.InetSocketAddress;

import org.apache.log4j.Logger;
import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

import com.hoolai.qps.codes.mina.protobuf.ProtobufCodecFactory;
import com.hoolai.qps.proto.ReqCmdProto.SaveUserReqCmdProto;

public class LogicServer {

    private static final Logger logger = Logger.getLogger(LogicServer.class);

    public static void main(String[] args) throws IOException {
        IoAcceptor acceptor = new NioSocketAcceptor();

        acceptor.getFilterChain().addLast("logger", new LoggingFilter());
        acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(ProtobufCodecFactory.newInstance(SaveUserReqCmdProto.newBuilder().build())));

        acceptor.setHandler(new LogicServerHandler());
        acceptor.getSessionConfig().setReadBufferSize(2048);
        acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 60);
        acceptor.bind(new InetSocketAddress("127.0.0.1", 1111));
        logger.info("logic server start!");
    }

    public static class LogicServerHandler extends IoHandlerAdapter {
        @Override
        public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
            logger.error("exception caught:" + cause.getMessage());
        }

        @Override
        public void messageReceived(IoSession session, Object message) throws Exception {
            logger.info("logic message reviced:\n" + message);
            session.write(message);
        }

        @Override
        public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
            logger.debug("IDLE " + session.getIdleCount(status));
        }
    }

}
